package com.zspringboot.demo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zspringboot.demo.common.Result;
import com.zspringboot.demo.entity.Role;
import com.zspringboot.demo.service.IRoleService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author laolang
 * @since 2024-02-25
 */
@RestController
@RequestMapping("/role")
public class RoleController {


    @Resource
    private IRoleService roleService;

    // 新增/修改
    @PostMapping
    public Result save(@RequestBody Role role) {
            return Result.success(roleService.saveOrUpdate(role));
            }

    // 删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
            return Result.success(roleService.removeById(id));
            }
    // 批量删除
    @PostMapping("/del/batch")
    public Result deleteBacth(@RequestBody List<Integer> ids){
        return Result.success(roleService.removeByIds(ids));
        }
    // 查询所有数据
    @GetMapping
    public Result findAll() {
            return Result.success(roleService.list());
            }

    // 根据id 查询
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
            return Result.success(roleService.getById(id));
            }

    // 分页
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name) {
            QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("id");
            if (!"".equals(name))
                queryWrapper.like("name",name);

            return Result.success(roleService.page(new Page<>(pageNum, pageSize),queryWrapper));
            }
    /**
     * 绑定角色和菜单的关系
     * @param roleId 角色id
     * @param menuIds 菜单ids
     * @return
     */
    @PostMapping("/roleMenu/{roleId}")
    public Result roleMenu(@PathVariable Integer roleId,
                           @RequestBody List<Integer> menuIds){
        roleService.setRoleMenu(roleId,menuIds);
        return Result.success();
    }
    @GetMapping("/roleMenu/{roleId}")
    public Result roleMenu(@PathVariable Integer roleId){

        return Result.success(roleService.getRoleMenu(roleId));
    }
}

